#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct row
{
	int row_index;
	struct row *next;
};

typedef struct word_node
{
	char *word;
	int num;
	row *head, *tail;
};

#define MAX_WORD 100
typedef struct word_list
{
	word_node wn[MAX_WORD];
	int num;
};
word_list wl;

void initail()
{
	wl.num = 0;
	FILE *fp;
	if ((fp = fopen("word", "r")) == NULL)
		exit(EXIT_FAILURE);
	char temp_word[20];
	while ((fscanf(fp, "%19s", temp_word) == 1))
	{
		int n = wl.num++;
		wl.wn[n].word = (char *)malloc(sizeof(char) * strlen(temp_word));
		strcpy(wl.wn[n].word, temp_word);
		wl.wn[n].head = wl.wn[n].tail = NULL;
	}
}

//  words and row
void insert(char *word, int r)
{
	for (int i = 0; i < wl.num; i++)
	{
		if (strcmp(word, wl.wn[i].word) == 0)
		{
			wl.wn[i].num++;
			row *new_row = (row *)malloc(sizeof(row));
			new_row->row_index = r;
			new_row->next = NULL;
			if (wl.wn[i].head == NULL)
			{
				wl.wn[i].head = new_row;
				wl.wn[i].tail = new_row;
			}
			else if (wl.wn[i].tail->row_index != new_row->row_index)
			{
				wl.wn[i].tail->next = new_row;
				wl.wn[i].tail = new_row;
			}
			break;
		}
	}
}
void assistant()
{
	FILE *fp;
	if ((fp = fopen("words.txt", "r")) == NULL)
		exit(EXIT_FAILURE);
	int row = 0;
	char buf[1024];
	char word[20];
	while (fgets(buf, 1024, fp))
	{
		int i = 1;
		while (buf[i] != '\n' && buf[i] != '\0')
		{
			int k = 0;
			while (buf[i] != ' ' && buf[i] != '\n')
			{
				word[k++] = buf[i++];
			}
			word[k] = '\0';
			i++;
			insert(word, row);
		}
		row++;
	}
}

void print_list()
{
	for (int i = 0; i < wl.num; i++)
	{
		printf("%-10s taotal:%d\t", wl.wn[i].word, wl.wn[i].num);
		row *t = wl.wn[i].head;
		while (t)
		{
			printf("->%-2d  ", t->row_index);
			t = t->next;
		}
		printf("\n");
	}
}
int main()
{
	/*******************code*******************/
	initail();
	assistant();
	print_list();
	/******************************************/
	printf("\n\n****************************\n");
	printf("Press Enter key to continue\n");
	getchar();
	return 0;
	/******************************************/
}
